package br.usp.icmc.biomac.client.view;

import java.util.ArrayList;
import java.util.List;

import br.usp.icmc.biomac.shared.ROI;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ProvidesKey;
import com.google.gwt.view.client.SelectionModel;
import com.google.gwt.view.client.SingleSelectionModel;

public class ImageROIcell extends Composite {

	private static ImageROIcellUiBinder uiBinder = GWT
			.create(ImageROIcellUiBinder.class);
	List<ROI> rois = new ArrayList<ROI>();
	
	TextCell textCell = new TextCell();

	@UiField(provided = true)
	CellList<ROI> cellList;
	@UiField SimplePager pager;

	interface ImageROIcellUiBinder extends UiBinder<Widget, ImageROIcell> {
	}

	/*
	 * Define a key provider for a Contact. We use the unique ID as the key,
	 * which allows to maintain selection even if the name changes.
	 */
	ProvidesKey<ROI> keyProvider = new ProvidesKey<ROI>() {
		@Override
		public Object getKey(ROI item) {
			// Always do a null check.
			return (item == null) ? null : item.getLabel();
		}
	};

	private static class ROIcell extends AbstractCell<ROI> {
		@Override
		public void render(Context context, ROI value, SafeHtmlBuilder sb) {
			if (value != null) {
				sb.appendEscaped(value.getLabel());

			}
		}
	}

	public ImageROIcell() {
		cellList = new CellList<ROI>(new ROIcell(), keyProvider);
		initWidget(uiBinder.createAndBindUi(this));
		pager.setDisplay(cellList);
	}
	
	public void loadCellList(){
		// Push data into the CellList.
	    cellList.setRowCount(rois.size(), true);
	    cellList.setRowData(0, rois);

	    // Add a selection model using the same keyProvider.
	    SelectionModel<ROI> selectionModel = new SingleSelectionModel<ROI>(
	        keyProvider);
	    cellList.setSelectionModel(selectionModel);
	}
	
	public void updateCellList(List<ROI> rois){
		this.rois = rois;
	    cellList.setRowCount(rois.size(), true);
	    cellList.setRowData(0, rois);
		cellList.redraw();
	}

}
